# -*- coding:utf8 -*-

"""
    Copyright 2010 Yurtaev Egor

    This file is part of webapp-dcpp-log.

    webapp-dcpp-log is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 2 of the License, or
    (at your option) any later version.

    webapp-dcpp-log is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with webapp-dcpp-log. If not, see http://www.gnu.org/licenses/.
"""

import re
import urllib
from smile import smiles

def smile(text):
    itr = 0
    text = " " + text
    for smile in smiles:
        try:
            text = text.replace(unicode(" " + smile[0], "utf-8"), """ <img src='/static/Smiles/""" + unicode(smile[1], "utf-8") + "'></img>")
        except:
            print "Error: " + str(itr) + "smile"
        itr = itr + 1
    return text


def magnet(text):
    true_text = text
    dic_magnet = re.findall("(magnet:\?\w+[^\s\[\]\"]+)", true_text)
    for i in dic_magnet:
        s = re.findall("((?<=&dn=)+.*)", i)[0]
        #raz = str(int(re.findall("((?<=&xl=)+\d+)", i)[0])/1024/1024)
        int_raz = float(re.findall("((?<=&xl=)+\d+)", i)[0])
        if (int_raz > 1000):
            raz = str(round(int_raz / 1024, 2)) + " Kb"
        if (int_raz > 1000000):
            raz = str(round(int_raz / 1024 / 1024, 2)) + " Mb"
        if (int_raz > 1000000000):
            raz = str(round(int_raz / 1024 / 1024 / 1024, 2)) + " Gb"
        true_text = true_text.replace(i, "<a href=\'" + i + "\'>" + unicode(urllib.unquote(str(s)), "utf-8") + " (" + raz + ")" + "</a>") # так как urllib.unquote не понимает юникод, то необходимо преобразовывать в строку а потом обратно
    return true_text


def http(text):
    true_text = text
    dic_http = re.findall("""(http://[^\s]+)""", true_text)
    for i in dic_http:
        true_text = true_text.replace(i, "<a href='" + i + "'>" + i + "</a>")
    return true_text


def all(text):
    text_true = text
    text_true = smile(text_true)
    text_true = magnet(text_true)
    text_true = http(text_true)
    return text_true